package com.ripservice.controller;

import com.ripservice.dto.RoutingTableDto;
import com.ripservice.dto.SimulationDto;
import com.ripservice.entity.SimulationEntity;
import com.ripservice.service.SimulationService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 控制器类，用于处理RIP模拟相关的HTTP请求
 */
@RestController
@RequestMapping("/api/simulations")
@RequiredArgsConstructor
public class SimulationController {

    /**
     * 模拟服务实例，用于执行具体的模拟逻辑
     */
    private final SimulationService simulationService;

    /**
     * 启动一个新的RIP模拟
     *
     * @param topologyId 拓扑ID，用于标识要启动的网络拓扑结构
     * @return ResponseEntity 包含模拟ID的响应实体
     */
    @PostMapping("/{topologyId}/start")
    public ResponseEntity<Long> start(@PathVariable("topologyId") Long topologyId) {
        Long simId = simulationService.startSimulation(topologyId);
        return ResponseEntity.ok(simId);
    }

    /**
     * 获取指定路由器的路由表信息
     *
     * @param simulationId 模拟ID
     * @param routerId     路由器ID
     * @return ResponseEntity 包含路由表数据传输对象的响应实体
     */
    @GetMapping("/{simulationId}/routers/{routerId}/routing-table")
    public ResponseEntity<RoutingTableDto> getRoutingTable(@PathVariable("simulationId") String simulationId,
                                                           @PathVariable("routerId") String routerId) {
        RoutingTableDto dto = simulationService.getRoutingTable(simulationId, routerId);
        return ResponseEntity.ok(dto);
    }

    /**
     * 停止指定的RIP模拟
     *
     * @param simulationId 模拟ID
     * @return ResponseEntity 表示操作成功的响应实体
     */
    @PostMapping("/stop/{simulationId}")
    public ResponseEntity<Void> stop(@PathVariable("simulationId") String simulationId) {
        simulationService.stopSimulation(simulationId);
        return ResponseEntity.ok().build();
    }

    /**
     * 获取所有仿真实例的历史记录列表
     *
     * @return ResponseEntity 包含所有仿真实例列表的响应实体
     */
    @GetMapping
    public ResponseEntity<List<SimulationEntity>> getAllSimulations() {
        return ResponseEntity.ok(simulationService.getAllSimulations());
    }

    /**
     * 根据拓扑ID获取相关的所有仿真实例记录
     *
     * @param topologyId 拓扑ID
     * @return ResponseEntity 包含该拓扑下所有仿真实例列表的响应实体
     */
    @GetMapping("/topology/{topologyId}")
    public ResponseEntity<List<SimulationEntity>> getSimulationsByTopology(@PathVariable("topologyId") Long topologyId) {
        return ResponseEntity.ok(simulationService.getSimulationsByTopology(topologyId));
    }

    /**
     * 删除指定ID的仿真实例及其相关数据
     *
     * @param simulationId 模拟ID
     * @return ResponseEntity 表示操作成功的响应实体
     */
    @DeleteMapping("/{simulationId}")
    public ResponseEntity<Void> delete(@PathVariable("simulationId") String simulationId) {
        simulationService.deleteSimulation(simulationId);
        return ResponseEntity.ok().build();
    }
}